import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Like, Repository } from 'typeorm';
import BaseWorkType from '@main/entities/service/admin/base/base-work-type.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
import BaseShiftUser from '@main/entities/service/admin/base/base-shift-user.entity';
import { generateExcelFn } from '@main/excel';
import { SysOperationLogService } from '../../system/operationLog/operationLog.service';

@Injectable()
export class BaseWorkTypeService {
  constructor(
    @InjectRepository(BaseWorkType)
    private workTypeRepository: Repository<BaseWorkType>,
    @InjectRepository(BaseShiftUser)
    private shiftUserRepository: Repository<BaseShiftUser>,
    private operationLogService: SysOperationLogService
  ) {}

  async list() {
    return await this.workTypeRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { workTypeName, workTypeCode, ids = [] } = entity;

    const where = {
      workTypeName: Like(`%${workTypeName}%`),
      workTypeCode: Like(`%${workTypeCode}%`),
    };

    if (ids && ids.length) {
      where['workTypeCode'] = In(ids);
    }
    const [list, total] = await this.workTypeRepository.findAndCount({
      where,
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });

    return [list, total];
  }

  async export(dto, lang) {
    const [list] = await this.page(dto);

    if (!list || !(list as any).length) {
      throw new ApiException(10052);
    }

    const dataList = list;

    return await generateExcelFn(
      {
        sheetName: 'workType',
        mainHeaderList: [
          {
            label: 'workTypeName',
          },
          {
            label: 'workTypeCode',
          },
          {
            label: 'remark',
          },
        ],
        dataList,
      },
      lang
    );
  }

  /**
   * 新增
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const workType = await this.workTypeRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'BaseWorkType',
      checkOnlyKeyList: [],
      data: workType,
      whereObj: null,
      remark: `BaseWorkType表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `岗位管理模块新增岗位`,
        databaseOperationLogList,
        remark: `新增岗位${data.workTypeName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新
   */
  async update(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const { id, workTypeName, standardHour, standardCost, remark } = data;

    await this.workTypeRepository.update(
      { id },
      {
        workTypeName,
        standardHour,
        standardCost,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );
    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'BaseWorkType',
      checkOnlyKeyList: [],
      data: {
        workTypeName,
        standardHour,
        standardCost,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      },
      whereObj: { id },
      remark: `BaseWorkType表更新岗位信息`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `岗位管理模块更新岗位信息`,
        databaseOperationLogList,
        remark: `更新岗位${data.workTypeName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除
   */
  async delete(idList, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const workTypeCodeList = idList.map((code) => {
      return {
        workTypeCode: code,
      };
    });
    const list = await this.workTypeRepository.find({
      where: workTypeCodeList,
    });
    const ids = list.map((item) => item.id);
    await this.workTypeRepository.delete(ids);
    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'BaseWorkType',
      checkOnlyKeyList: [],
      data: null,
      whereObj: idList,
      remark: `BaseWorkType表删除岗位`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `岗位管理模块删除岗位`,
        databaseOperationLogList,
        remark: `删除岗位`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  async isExistKey(workTypeCode: string) {
    const result = await this.workTypeRepository.findOne({ where: { workTypeCode } });

    if (result) throw new ApiException(10028);
  }

  async isExistKey2(idList) {
    for (let i = 0; i < idList.length; i++) {
      const result2 = await this.shiftUserRepository.findOne({
        where: { workTypeCode: idList[i] },
      });

      if (result2) throw new ApiException(10029);
    }
  }
}
